package com.example.demoback.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demoback.common.Constants;
import com.example.demoback.controller.dto.PasswordDto;
import com.example.demoback.controller.dto.PeopleDto;
import com.example.demoback.controller.dto.UserDto;
import com.example.demoback.entity.Menu;
import com.example.demoback.entity.People;
import com.example.demoback.entity.User;
import com.example.demoback.exception.ServiceException;
import com.example.demoback.mapper.PeopleMapper;
import com.example.demoback.mapper.RoleMapper;
import com.example.demoback.mapper.RoleMenuMapper;
import com.example.demoback.mapper.UserMapper;
import com.example.demoback.service.IMenuService;
import com.example.demoback.service.IPeopleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demoback.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yyd
 * @since 2022-07-01
 */
@Service
public class PeopleServiceImpl extends ServiceImpl<PeopleMapper, People> implements IPeopleService {

    private static final Log LOG = Log.get();

    @Resource
    private PeopleMapper peopleMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private IMenuService menuService;

    @Override
    public PeopleDto login(PeopleDto peopleDto) { //如果存在一条数据，则返回UserDto
//        // 用户密码 md5加密
//        userDto.setPassword(SecureUtil.md5(userDto.getPassword()));
        People one = getPeopleInfo(peopleDto);
        if (one != null) {
            BeanUtil.copyProperties(one, peopleDto, true);
//             设置token
            String token = TokenUtils.genToken(one.getPeopleids(), one.getPeoplepassword()); //传入id ，密码进token
            peopleDto.setToken(token);


            String role = one.getPeopleposition(); // ROLE_ADMIN 获取当前权限
            // 设置用户的菜单列表
            List<Menu> roleMenus = getRoleMenus(role);
            peopleDto.setMenus(roleMenus);
            return peopleDto;
        } else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }
    }

    public People getPeopleInfo(PeopleDto peopleDto) {  //查询出一条数据
        QueryWrapper<People> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("peopleids", peopleDto.getPeopleids());
        queryWrapper.eq("peoplepassword", peopleDto.getPeoplepassword());
        People one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "存在多条信息");
        }
        return one;
    }

    /**
     * 获取当前角色的菜单列表
     * @param roleFlag
     * @return
     */
    private List<Menu> getRoleMenus(String roleFlag) {
        Integer roleId = roleMapper.selectByFlag(roleFlag);
        // 当前角色的所有菜单id集合
        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);

        // 查出系统所有的菜单(树形)
        List<Menu> menus = menuService.findMenus("");
        // new一个最后筛选完成之后的list
        List<Menu> roleMenus = new ArrayList<>();
        // 筛选当前用户角色的菜单
        for (Menu menu : menus) {
            if (menuIds.contains(menu.getId())) {
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();
            // removeIf()  移除 children 里面不在 menuIds集合中的 元素
            children.removeIf(child -> !menuIds.contains(child.getId()));
        }
        return roleMenus;
    }

    @Override
    public void updatePassword(PasswordDto passwordDto) {
        int update = peopleMapper.updatePassword(passwordDto);
        if (update < 1) {
            throw new ServiceException(Constants.CODE_600, "密码错误");
        }
    }

}
